﻿using System.Linq;
using System.Xml.Linq;

namespace ExcelAutomator.Validation
{
	public class XmlValidator : BaseValidator
	{
		private readonly XDocument m_XDoc;

		public XmlValidator(string xml)
		{
			m_XDoc = XDocument.Parse(xml);
		}

		public XmlValidator(XDocument xDocument)
		{
			m_XDoc = xDocument;
		}

		public XmlValidator AttributeExists(string attributeName)
		{
			var element = m_XDoc.Elements().FirstOrDefault();
			if (element != null)
			{
				XAttribute attribute;
				if(!element.TryGetAttribute(attributeName, out attribute))
				{
					SetFailure(string.Format("The attribute {0} doesn't exists", attributeName), m_XDoc.ToString());
				}
			}
			return this;
		}

		public XmlValidator AttributeValueIsNotNull(string attributeName)
		{
			var element = m_XDoc.Elements().FirstOrDefault();
			if (element != null)
			{
				string value;
				if (element.TryGetAttributeValue(attributeName, out value))
				{
					if (value.IsNOE())
					{
						SetFailure(string.Format("The value of attribute '{0}' is null or empty.", attributeName), m_XDoc.ToString());
					}
				}
			}
			return this;
		}
	}
}